/*
 * main.c
 *
 *  Created on: 2017
 *      Author: zjm
 */

#include "mongoose.h"
#include "tabs/param.h"

static const char *s_http_port = "8800";
static struct mg_serve_http_opts s_http_server_opts;

const struct param_data _param_data[] = {
	PARAM_LIST
};

const struct action _action_data[] = {
	ACTION_LIST
};

static void handle_ssi_call(struct mg_connection *nc, const char *param) {
	printf("param:%s\n",param);
	for (int i = 0; i < ARRAY_SIZE(_param_data); ++i) {
		if(!strcmp(param,_param_data[i].param)){
			_param_data[i].cb(nc);
			return ;
		}
	}

	fprintf(stderr,"can't find param named:%s\n",param);
}

static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
  struct http_message *hm = (struct http_message *) ev_data;

  switch (ev) {
    case MG_EV_HTTP_REQUEST:{
    	for (int i = 0; i < ARRAY_SIZE(_action_data); ++i) {
    		if(mg_vcmp(&hm->uri,_action_data[i].url) == 0){
    			printf("url:%.*s\n",hm->uri.len,hm->uri.p);
    			printf("query:%.*s\n",hm->query_string.len,hm->query_string.p);
    			_action_data[i].cb(nc,hm);
    			return ;
    		}
    	}

        mg_serve_http(nc, hm, s_http_server_opts); /* Serve static content */
      }
      break;
    case MG_EV_SSI_CALL:
      handle_ssi_call(nc, ev_data);
      break;
    default:
      break;
  }
}

int main(void)
{
	struct mg_mgr mgr;
	struct mg_connection *nc;

	mg_mgr_init(&mgr, NULL);

	nc = mg_bind(&mgr, s_http_port, ev_handler);
	mg_set_protocol_http_websocket(nc);
	s_http_server_opts.document_root = "/data/web";
	s_http_server_opts.auth_domain = "lhloao.com";
	s_http_server_opts.global_auth_file = ".htpasswd";
	s_http_server_opts.ssi_pattern = "**.shtml$|**.shtm$|**.js$";

	for (;;) {
		mg_mgr_poll(&mgr, 1000);
	}
	mg_mgr_free(&mgr);

	return 0;
}
